package fun.qu_an.minecraft.mini_games_helper.client;

import fun.qu_an.minecraft.mini_games_helper.client.config.MiniGamesHelperClientConfig;
import fun.qu_an.minecraft.mini_games_helper.client.handle.ForceOptionHelperSodium;
import fun.qu_an.minecraft.mini_games_helper.client.handle.ForceOptionHelperVanilla;
import fun.qu_an.minecraft.mini_games_helper.config.MiniGamesHelperConfig;
import fun.qu_an.minecraft.mini_games_helper.network.MGHConfigS2CPacket;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.networking.v1.ClientConfigurationNetworking;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerInteractionManager;

@Environment(EnvType.CLIENT)
public class MiniGamesHelperClient implements ClientModInitializer {
	@Override
	public void onInitializeClient() {
		// applied on server login
		ClientConfigurationNetworking.registerGlobalReceiver(MGHConfigS2CPacket.TYPE.getId(), (client, handler, buf, responseSender)
			-> {
			// TODO move to MGHConfigS2CPacket
			MGHConfigS2CPacket packet = MGHConfigS2CPacket.receiveFromServer(buf);
			// received as FabricPacket
			packet.onReceive();
			System.out.println("received!");
		});

		// applied on server reload
		ClientPlayNetworking.registerGlobalReceiver(MGHConfigS2CPacket.TYPE, (packet, player, responseSender) -> {
			packet.onReceive();
			ClientPlayerInteractionManager interactionManager = MinecraftClient.getInstance().interactionManager;
			if (interactionManager == null) {
				return;
			}
			ForceOptionHelperVanilla.apply(interactionManager.getCurrentGameMode());
			ForceOptionHelperSodium.apply(interactionManager.getCurrentGameMode());
		});

		ClientPlayConnectionEvents.JOIN.register((handler, sender, client)
			-> client.execute(() -> {
			ClientPlayerInteractionManager interactionManager = client.interactionManager;
			if (interactionManager == null) {
				return;
			}
			ForceOptionHelperVanilla.apply(interactionManager.getCurrentGameMode());
			ForceOptionHelperSodium.apply(interactionManager.getCurrentGameMode());
			System.out.println("imanager is not null!");
		}));
		ClientPlayConnectionEvents.DISCONNECT.register((handler, client)
			-> {
			MiniGamesHelperClientConfig.reset();
			ForceOptionHelperVanilla.revoke();
			ForceOptionHelperSodium.revoke();
			System.out.println("reset!!!!!");
		});
	}
}
